package com.xiao.rabbitmq.rabbit;

import com.rabbitmq.client.Channel;
import com.xiao.rabbitmq.utils.JsonTool;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author victor
 * @desc 死信接收处理消费者
 */
@Component
@RabbitListener(queues = MQConstant.DEFAULT_REPEAT_TRADE_QUEUE_NAME)
public class TradeProcessor {

    @Autowired
    private IMessageQueueService messageQueueService;

    @RabbitHandler
    public void process(String content, Channel channel, Message message) throws IOException {
        System.out.println(content);

        // 这里是死信转发的队列， 在这里进行一个中转，最终转发到对应的队列处理对应的业务
        DLXMessage temp = JsonTool.getJsonObject(content, DLXMessage.class);

        if (temp == null) return;
        messageQueueService.send(temp.getQueueName(), temp.getContent());

        try {
            // 告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("delay  receiver success");
        } catch (IOException e) {
            e.printStackTrace();
            // 丢弃这条消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            System.out.println("delay  receiver fail");
        }
    }
}

